package com.chengyu.core.util.ali;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.chengyu.core.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;

/**
 * HttpClient工具类
 *
 * @author sunruishan
 */
@Component
@Slf4j
public class NewHttpClientUtil {

    //    @Autowired
//    private static CloseableHttpClient httpClient;
    private static CloseableHttpClient httpClient = null;

    private static AlipayClient alipayClient = null;


    // 1. 填入appid
    @Value("${alipay.APPID}")
    private  String APPID;
    // 2. 填入应用私钥
    @Value("${alipay.PRIVATE_KEY}")
    private  String PRIVATE_KEY;
    // 3. 填入支付宝公钥
    @Value("${alipay.ALIPAY_PUBLIC_KEY}")
    private  String ALIPAY_PUBLIC_KEY;
    // 4. 填入支付宝接口内容加密方式
    @Value("${alipay.aesSecretKey}")
    private  String aesSecretKey;


    static {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        // 总连接池数量
        connectionManager.setMaxTotal(150);
        // 可为每个域名设置单独的连接池数量
        // connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost("xx.xx.xx.xx")), 80);
        // setConnectTimeout：设置建立连接的超时时间
        // setConnectionRequestTimeout：从连接池中拿连接的等待超时时间
        // setSocketTimeout：发出请求后等待对端应答的超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1000)
                .setConnectionRequestTimeout(2000)
                .setSocketTimeout(3000)
                .build();
        // 重试处理器，StandardHttpRequestRetryHandler
        HttpRequestRetryHandler retryHandler = new StandardHttpRequestRetryHandler();

        httpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig)
                .setRetryHandler(retryHandler).build();

//        alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
//                APPID,
//                PRIVATE_KEY,
//                "json",
//                "UTF-8",
//                ALIPAY_PUBLIC_KEY
//                , "RSA2");
    }

    public AlipayClient getAlipayClient(){
        if (alipayClient == null){
            alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                    APPID,
                    PRIVATE_KEY,
                    "json",
                    "UTF-8",
                    ALIPAY_PUBLIC_KEY
                    , "RSA2");
            return alipayClient;
        }else {
            return alipayClient;
        }
    }


    public String doGet(String url, Map<String, String> param, Map<String, String> headers, Map<String, String> basic) {

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            builder.setCharset(StandardCharsets.UTF_8);
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            if (headers != null && !headers.isEmpty()) {
                headers.forEach(httpGet::setHeader);
            }
            if (basic != null && !basic.isEmpty()) {
                httpGet.addHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((basic.get("username") + ":" + basic.get("password")).getBytes()));
            }

            // 执行请求
            response = httpClient.execute(httpGet);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            log.error("HttpClient-Get请求-完成，url:{},param:{},headers:{},resultString:{}", url, param, headers, resultString);
        } catch (Exception e) {
            log.error("HttpClient-Get请求-异常，url:{},param:{},headers:{}", url, param, headers, e);
            throw new BusinessException("HttpClient-Get请求异常");
        } finally {
            try {
                close(response);
                // httpClient.close();
            } catch (Exception e) {
                log.error("HttpClient-Get请求-close异常，url:{},param:{},headers:{}", url, param, headers, e);
                throw new BusinessException("HttpClient-Get请求异常");
            }
        }
        return resultString;
    }


    public String doPost(String url, Map<String, String> param, Map<String, String> headers) {
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, StandardCharsets.UTF_8);
                httpPost.setEntity(entity);
            }

            if (headers != null && !headers.isEmpty()) {
                headers.forEach(httpPost::setHeader);
            }

            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            log.info("HttpClient-Post请求-完成，url:{},param:{},headers:{},resultString:{}", url, param, headers, resultString);
        } catch (Exception e) {
            log.error("HttpClient-Post请求-异常，url:{},param:{},headers:{}", url, param, headers, e);
            throw new BusinessException("HttpClient-Post请求异常");
        } finally {
            close(response);
        }
        return resultString;
    }

    private void close(CloseableHttpResponse response) {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            log.error("HttpClient-response.close", e);
        }
    }

    public String doPost(String url) {
        return doPost(url, null, null);
    }

    public String doPostJson(String url, String json, Map<String, String> headers, Map<String, String> basic) {
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, StandardCharsets.UTF_8);
            entity.setContentType("application/json");
            entity.setContentEncoding("application/json");
            httpPost.setEntity(entity);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
            httpPost.addHeader("accept", "application/json");
            if (headers != null && !headers.isEmpty()) {
                headers.forEach(httpPost::setHeader);
            }
            if (basic != null && !basic.isEmpty()) {
                httpPost.addHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((basic.get("username") + ":" + basic.get("password")).getBytes()));
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            log.info("HttpClient-doPostJson请求-完成，url:{},json:{},headers:{},resultString:{}", url, json, headers, resultString);
        } catch (Exception e) {
            log.error("HttpClient-doPostJson请求-异常，url:{},json:{},headers:{}", url, json, headers, e);
            throw new BusinessException("HttpClient-doPostJson请求");
        } finally {
            close(response);
        }
        return resultString;
    }
}
